<style lang="less">
@import '../style.less';
</style>

<template>
	<div class="citation-training">
		<ul v-if="operation_state">
			<span v-if="operationType!=''">
				<li :key="item.sort" v-for="item in citationTestList" v-if="operationType ==item.sort">
					<span>{{item.title}}</span>
					<el-button @click="start(item.sort,item.title)">开始练习</el-button>
				</li>
			</span>
			<span v-else>
				<li :key="item.sort" v-for="item in citationTestList">
					<span>{{item.title}}</span>
					<el-button @click="start(item.sort,item.title)">开始练习</el-button>
				</li>
			</span>
			<li class="test-bottom" v-if="operationType==''">
				<span>练习成绩</span>
				——
				<span @click="showGrade">显示成绩</span>
			</li>
		</ul>
		<div class="test-detail" v-else>
			<h4>
				传票翻打- 学习模式
				<span>【{{whichRow}}】</span>
			</h4>

			<div class="test-detail-main">
				<div class="citation-show">
					<el-col :span="12">
						<h5>
							银行柜台职业资格培训
							<br />传票翻打练习题
						</h5>
						<div :class="sortState=='firstLineList'?' boder-1px   col-one':'col-one'">
							(一)
							<br />
							<p>
								<span>
									人民币
									<br />(大写)
								</span>
								{{numblist.firstLineList?numblist.firstLineList[0].chineseCharacters:''}}
							</p>
						</div>
						<div :class="sortState=='secondLineList'?' boder-1px   col-one':'col-one'">
							(二)
							<br />
							<p>
								<span>
									人民币
									<br />(大写)
								</span>
								{{numblist.secondLineList?numblist.secondLineList[0].chineseCharacters:''}}
							</p>
						</div>
					</el-col>
					<el-col :offset="2" :span="10">
						<div :class="sortState=='thirdLineList'?' boder-1px   col-two':'col-two'">
							(三)
							<br />
							<div>
								<p>
									<span v-for="item in moneyList">{{item}}</span>
								</p>
								<p>
									<span v-for="item in spanList"></span>
									<em>{{numblist.thirdLineList?Math.ceil(numblist.thirdLineList[0]*100,10):''}}</em>
								</p>
							</div>
						</div>
						<div :class="sortState=='fourthLineList'?' boder-1px   col-two':'col-two'">
							(四)
							<br />
							<div>
								<p>
									<span v-for="item in moneyList">{{item}}</span>
								</p>
								<p>
									<span v-for="item in spanList"></span>
									<em>{{numblist.fourthLineList?Math.ceil(numblist.fourthLineList[0]*100):''}}</em>
								</p>
							</div>
						</div>
						<div :class="sortState=='fifthLineList'?' boder-1px   col-two':'col-two'">
							(五)
							<br />
							<div>
								<p>
									<span v-for="item in moneyList">{{item}}</span>
								</p>
								<p>
									<span v-for="item in spanList"></span>
									<em>{{numblist.fifthLineList?Math.ceil(numblist.fifthLineList[0]*100):''}}</em>
								</p>
							</div>
						</div>
					</el-col>
				</div>
				<div class="citation_data_operation" style="width:100%">
					<div class="test-detail-data_show">
						<el-col :span="10" class="data_show">
							<span>
								第
								<i style="color:#409EFF">{{numLength}}</i> 个
							</span>
							<span>共{{numbLength}}个</span>
							<br />
							<span>
								错
								<i style="color:red">{{testResult.inputErrorNum}}</i> 个
							</span>
						</el-col>
						<el-col :mt="4" :span="22" class="text-r" v-if="operationType==''">
							<span @click="showGrade" class="checkGrade_citation">查看成绩</span>
						</el-col>
					</div>
					<el-col :span="11" class="el-progress-box float-r">
						<p>
							<el-progress :percentage="percenting" :show-text="false" :stroke-width="40" :text-inside="true" color="#f26522"></el-progress>
							<span class="test-detail-main-time">{{countDown}}</span>
						</p>
						<el-form @submit.native.prevent="enterKey">
							<el-input :disabled="inputFlag" maxlength="18" placeholder="0.00" ref="gain" v-model.trim="num"></el-input>
						</el-form>
						<el-col :span="11" class="data_operation citation_data_operation">
							<el-button :disabled="disable" @click="outTest" size="medium">退出</el-button>
							<el-button :disabled="disable" @click="startTest" size="medium" type="primary">{{testFlag?'开始':'结束'}}</el-button>
						</el-col>
					</el-col>
				</div>
				<!-- <el-footer>1111</el-footer> -->
			</div>
		</div>
	</div>
</template>

<script>
/**
 * 传票翻打
 */
import { mapGetters, mapActions, mapMutations } from 'vuex'
import { citationTestList, moneyList, spanList } from '../config'
import { Base64 } from 'js-base64'
import { keepTwoDecimalFull } from '@/utils/util'
import moment from 'moment'
// import { mapGetters, mapActions, mapMutations } from "vuex";

export default {
  name: 'citation-training',
  data() {
    return {
      /** initData */
      operationType: this.$route.query.operationType
        ? this.$route.query.operationType
        : '',
      operation_state: true,
      testNum: 0,
      citationTestList: citationTestList,
      moneyList: moneyList,
      spanList: spanList,
      numblist: {},
      numbLength: 0,
      sortState: '',
      whichRow: '',
      testFlag: true,
      inputFlag: true,
      active: 0,
      num: '',
      numLength: 1,
      time: 120,
      timeShow: '01:59',
      timepercent: 100,
      disable: false,
      getClientHeight: 0,
      testResult: {
        // 总输入
        inputNum: 0,
        // 错误数量
        inputErrorNum: 0,
        // 正确数量
        correctNumber: 0,
        result: [],
        timeDuration: 120
      }
    }
  },
  created() {},
  mounted() {},
  computed: {
    countDown() {
      return this.timeShow
    },
    percenting() {
      return this.timepercent
    }
  },
  methods: {
    ...mapActions(['summonsFn', 'uploadGradesFn']),
    loadInitData(type) {
      this.summonsFn({
        success: res => {
          if (JSON.stringify(res) == '{}') {
            this.$message({
              message: '请通知管理员上传传票翻打固定数据',
              type: 'warning'
            })
            setTimeout(() => {
              this.$router.go(-1)
            }, 3000)
          } else {
            this.numblist = res
            this.numbLength = res[type].length
          }
        }
      })
    },
    showGrade() {
      this.$emit('handleSelect', 'examineGrade', 'citation')
    },
    //  开始练习按
    start(type, whichRow) {
      this.timeShow = '01:59'
      this.timepercent = 100
      this.operation_state = false
      clearTimeout(window.timeRun)
      this.testFlag = true
      this.sortState = type
      this.whichRow = whichRow
      this.loadInitData(this.sortState)
    },
    // 考试考试
    startTest() {
      this.inputFlag = false
      if (this.testFlag) {
        this.testNum++
        this.initData()
        this.testNum > 1 && this.loadInitData(this.sortState)
        this.testFlag = false
        window.startTime = this.hasTime()
        window.tTime = this.getTime()
      } else {
        this.endTest()
      }
    },
    // 考试开始 input 输入考试内容
    enterKey() {
      if (this.testFlag) {
        return
      }
      this.testResult.inputNum++
      // 判断考试类型   第一行第二行
      if (
        this.sortState == 'firstLineList' ||
        this.sortState == 'secondLineList'
      ) {
        let sateData = this.numblist[this.sortState][0]
        this.num == sateData.number
          ? this.testResult.correctNumber++
          : this.testResult.inputErrorNum++

        this.testResult.result.push({
          question: sateData.chineseCharacters,
          consequence: this.num,
          id: this.numLength,
          state: this.num == sateData.number ? '正确' : '错误'
        })
      } else {
        // 判断考试类型   第三行第四行 第五行 做特殊数据处理
        let sateData = keepTwoDecimalFull(this.numblist[this.sortState][0])
        this.num == sateData
          ? this.testResult.correctNumber++
          : this.testResult.inputErrorNum++
        this.active <= this.numbLength &&
          this.testResult.result.push({
            question: sateData,
            consequence: this.num,
            id: this.numLength,
            state: this.num == sateData ? '正确' : '错误'
          })
      }
      this.num = ''
      this.active++
      this.numblist[this.sortState].shift()
      // 考试结束
      if (this.active >= this.numbLength) {
        this.endTest()
        return
      }
      this.numLength < this.numbLength && this.numLength++
    },
    // 退出考试
    outTest() {
      this.inputFlag = true
      this.operation_state = true
      this.testFlag = true
      clearTimeout(window.timeRun)
      ;(this.numblist = []), (this.numbLength = 0), this.initData()
    },
    // 开始考试时初始化数据
    initData() {
      if (this.testFlag) {
        this.numLength = 1
        this.testFlag = false
        this.time = 120
        this.timeShow = '01:59'
        this.timepercent = 100
        this.testResult = {
          inputNum: 0,
          inputErrorNum: 0,
          correctNumber: 0,
          result: [],
          timeDuration: 120
        }
        this.num = ''
        this.active = 0
        this.timer()
        this.$refs.gain.focus()
      } else {
        clearTimeout(window.timeRun)
        this.testFlag = true
      }
    },
    // 结束考试处理数据
    endTest() {
      this.inputFlag = true
      this.disable = true
      if (this.testFlag) {
        return false
      }
      clearTimeout(window.timeRun)
      if (
        this.sortState == 'firstLineList' ||
        this.sortState == 'secondLineList'
      ) {
        this.numblist[this.sortState].length &&
          this.numblist[this.sortState].map((item, index) => {
            this.testResult.result.push({
              question: item.chineseCharacters,
              consequence: '',
              id: this.testResult.inputNum + index + 1,
              state: '错误'
            })
          })
      } else {
        this.numblist[this.sortState].length &&
          this.numblist[this.sortState].map((item, index) => {
            this.testResult.result.push({
              question: keepTwoDecimalFull(item),
              consequence: '',
              id: this.testResult.inputNum + index + 1,
              state: '错误'
            })
          })
      }
      const timeout = 120 - this.time
      //错误率

      const errorRate =
        this.testResult.correctNumber > 0
          ? (
              (1 - this.testResult.correctNumber / this.numbLength) *
              1000
            ).toFixed(4)
          : 1000
      // 总速度
      const sumSpeed =
        this.testResult.inputNum > 0
          ? ((this.testResult.inputNum / timeout) * 3600).toFixed(2)
          : 0
      const effectiveSpeed =
        this.testResult.correctNumber > 0
          ? ((this.testResult.correctNumber / timeout) * 3600).toFixed(2)
          : 0
      this.testResult.errorRate = errorRate
      this.testResult.sumSpeed = sumSpeed
      this.testResult.effectiveSpeed = effectiveSpeed
      let examGrade = this.$store.state.login.data.loginUser.username
      let getdata = examGrade + '_citation'
      localStorage.setItem(getdata, JSON.stringify(this.testResult))
      !this.operationType && (this.disable = false)
      this.operationType && this.changeExam()
      window.eTime = this.getTime()
      // 上传成绩
      var data = {
        bankId: this.$store.state.login.data.loginUser.userInfo.bankId,
        comment: '',
        dataFlag: '1',
        enabled: this.$store.state.login.data.loginUser.userInfo.enabled,
        errorInput: this.testResult.inputErrorNum,
        errorRate: this.testResult.errorRate,
        totalInput: this.testResult.inputNum,
        totalInputSpeed: this.testResult.sumSpeed,
        type: this.operationType ? 'exam' : 'practice',
        validInputSpeed: this.testResult.effectiveSpeed,
        patternType: this.sortState,
        endTime: this.hasTime(),
        startTime: window.startTime,
        employeeId: this.$store.state.login.data.loginUser.userInfo.employeeId,
        name: 'citation',
        examId: this.examId,
        score: parseInt((1000 - this.testResult.errorRate * 1) / 10),
        spendTime: (window.eTime * 1 - window.tTime * 1) / 1000
      }
      this.$message({
        message: '正在上传结果',
        type: 'warning',
        center: true,
        duration: 1000,
        onClose: () => {
          this.uploadGradesFn({
            data,
            success: res => {
              setTimeout(() => {
                this.testFlag = true
                this.operationType &&
                  this.$router.replace({
                    name: 'traineeHome',
                    query: {
                      tabName: 'exam'
                    }
                  })
              }, 1000)
            }
          })
        }
      })
    },
    // 考试倒计时函数
    timer() {
      if (this.time > 0) {
        this.time--
        this.timepercent = this.timepercent - 10 / 12
        this.timeShow =
          '0' +
          Math.floor(this.time / 60) +
          ':' +
          (this.time % 60 > 9 ? this.time % 60 : '0' + (this.time % 60))
        window.timeRun = setTimeout(this.timer, 1000)
      } else if (this.time == 0) {
        this.timeShow = '00:00'
        this.timepercent = 0
        clearTimeout(window.timeRun)
        this.endTest()
      }
    },
    hasTime() {
      const format = 'YYYY-MM-DD HH:mm:ss.SSS'
      const timeData = moment()
      var time = moment(timeData).format(format)
      return time
    },
    getTime() {
      return Date.parse(new Date())
    },
    changeExam() {
      const { course } = this.$route.query
      if (!this.operationType && !course) return
      const { dispatch } = this.$store
      const query = JSON.parse(Base64.decode(course))
      const { trainingId, learningId, examId, examPaperId } = query
      this.examId = query.examId
      // 设置考试为完成参加
      dispatch('course/completeExam', examId)
      // 保存考试成绩
      const finalResult = {
        examinationId: examId,
        examinationPaperId: examPaperId,
        businessTemplateId: '100',
        opStartTime: window.startTime,
        opEndTime: window.endTime,
        score: parseInt((1000 - this.testResult.errorRate * 1) / 10),
        grade: ''
        // grade: parseInt((1000 - this.testResult.errorRate * 1) / 10)
      }
      console.log('exam final result >> ', finalResult)
      dispatch('course/submitExamStepResult', finalResult)
    }
  }
}
</script>
